import Vue from 'vue'
import Vuex from 'vuex'
import { getCar, getDetail } from '../api'

Vue.use(Vuex)


const myPlugin = store => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    // 每次 mutation 之后调用
    // mutation 的格式为 { type, payload }
    localStorage.setItem('localCar', JSON.stringify(state.localCar))
  })
}

export default new Vuex.Store({
  state: {
    car: [],
    detail: {},
    localCar: []
  },
  getters: {
    // 总数量
    tatalCount(state) {
      let count = 0;
      state.localCar.forEach(v => {
        count += v.count
      })
      return count || ''
    },
    // 总价钱
    tatalPrice(state) {
      let price = 0;
      state.localCar.forEach(v => {
        price += v.price * v.count
      })
      return price
    }
  },
  mutations: {
    SET_CAR(state, payload) {
      state.car = payload
      console.log('car', state.car);
    },
    SET_DETAIL(state, payload){
      state.detail = payload 
    },
    // 加入购物车
    ADD_LOCALCAR(state, data) {
      const { id } = data
      const item = state.localCar.find(item => item.id === id)
      if(item) {
        item.count++
      } else {
        state.localCar.push({
          ...data,
          count: 1
        })
      }
      console.log('购物车', state.localCar);
    }
  },
  actions: {
    async GET_CAR({ commit }) {
      const resp = await getCar()
      const { data } = resp.data

      commit('SET_CAR', data)
    },
    async GET_DETAIL({ commit }, rawData){
      const resp = await getDetail(rawData)
      const { data } = resp.data
      commit('SET_DETAIL', data)
    }
  },
  modules: {
  },
  plugins: [myPlugin]
})
